<?php

require 'models/Car.php';
require 'models/CarDetails.php';
require 'models/User.php';

class CarController extends BaseController {

    public function getUserCar($email) {
        $email = urldecode($email);
        $user = User::orm()->find_one($email);

        if (!$user || empty($user->vin)) {
            return array();
        }

        $vin = $user->vin;

        $car = Car::orm()->find_one($vin);
        $details = CarDetails::orm()->find_one($vin);

        return array('car' => $car->as_array(), 'details' => $details->as_array());
    }

    public function create() {
        $data = $_POST;

        // find the user
        $email = $data['email'];
        $user = User::orm()->find_one($email);

        if (!$user) {
            $this->reportErrors("No user with that email");
            return;
        }
        
        // start a db transaction
        $db = ORM::get_db();
        $db->beginTransaction();
        
        // create the car
        $car = Car::orm()->create();
        $car->setFields(Car::$fields, $data);
        try {
            $car->save();
        } catch(Exception $e) {
            $db->rollBack();
            $this->reportErrors("Transaction failed with message: {$e->getMessage()}");
            return;
        }
        
        // change the user VIN
        $user->vin = $data['vin'];
        try {
            $user->save();
        } catch(Exception $e) {
            $db->rollBack();
            $this->reportErrors("Transaction failed with message: {$e->getMessage()}");
            return;
        }
        
        $db->commit();
        $this->reportSuccess();
    }

    public function createDetails($vin) {
        
        $data = $_POST;
        // specify the details for the car
        $details = CarDetails::orm()->create();
        $details->setFields(CarDetails::$fields, $data);
        $details->vin = $vin;
        
        try {
            $details->save();
        } catch(Exception $e) {
            $this->reportErrors("DB operation failed with message: {$e->getMessage()}");
            return;
        }
        $this->reportSuccess();
        
    }
    
    public function getDetails($vin) {
        $details = CarDetails::orm()->find_one($vin);
        
        if($details) {
            return $details->as_array();
        }
    }
    
    public function updateDetails($vin) {
        
        $put = file_get_contents('php://input');
        $data = array();
        parse_str($put, $data);
        
        $details = CarDetails::orm()->find_one($vin);
        $whitelist = CarDetails::$modifiableFields;
        $details->setFields($whitelist, $data);
        $details->save();
        $this->reportSuccess();
    }

}
